package internal

import (
	"BJXM_Shooting/msg"
	"github.com/name5566/leaf/gate"
	"github.com/name5566/leaf/log"
)

func init() {
	skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
	skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
	skeleton.RegisterChanRPC("UserLogin", rpcUserLogin)
}

func rpcNewAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	// 建立一个结构
	a.SetUserData(new(User))
}

func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)

	switch a.UserData().(type) {
	case *User:
		user := a.UserData().(*User)
		if user == nil {
			return
		}
		if user.data == nil {
			log.Release("未登录玩家离开游戏:%s", a.RemoteAddr())
		} else {
			log.Release("用户登出:%v", user.data.Nickname)
			user.state = stateLogout
			//user.logout(user.data.Account)
		}
	}
}

// 登录完成后的后续操作
func rpcUserLogin(args []interface{}) {
	// 取出传进来的agent跟账号
	a := args[0].(gate.Agent)
	account := args[1].(string)
	// 检测网络是否关闭
	if a.UserData() == nil {
		return
	}

	// 检验是否重复登录,如果已经存在登录，则让旧的连接断开
	users.Lock()
	oldUser := users.data[account]
	users.Unlock()
	if oldUser != nil {
		m := &msg.S2C_Login{
			ID:  msg.S2C_ID_LoginRepeated,
			Msg: "被登录下线",
		}
		log.Release("被登录下线:%s", account)
		// 让旧的登录关闭
		oldUser.WriteMsg(m)
		oldUser.logout(account)
	}

	log.Release("账号登录:%s", account)
	// 登录,将ChanRPC发过来的赋值进来
	newUser := &User{}
	newUser.Agent = a
	newUser.LinearContext = skeleton.NewLinearContext()
	newUser.state = stateLogin
	a.SetUserData(newUser)
	users.Lock()
	users.data[account] = newUser
	users.Unlock()
	newUser.login(account)

}
